<?php
class FivechessController extends Zend_Controller_Action
{	
	/*
	 * Date: 2009.02.18
	 * Author:hanframe or 洪峰
	 * Email:hongfeng891027@163.com
	 * QQ:94526693
	 * Blog:http://hi.baidu.com/hanframe_ip
	 */
	function init()
	{	
	    $this->registry = Zend_Registry::getInstance();
	    $this->view = $this->registry['view'];
	    $this->view->baseUrl = $this->_request->getBaseUrl();
	    $this->view->imgdir = "/public/images/fivechess/";
		/*******************************
			*	status stand for
			* 0	game over or game stop
			* 1 game playing 
			* 3	host user ready
			* 4	guest user ready
			* 5	user want to swap the chessboard
			* 6 user want to regret prev step
			* 7 user give up 
			* 8 user want to draw this chess with you 	
		*******************************/
	    $this->CHESS_STATUS = array(
  			'GAME_OVER'=> 0,
				'GAME_PLAYING'=> 1,
				'HOST_READY'=> 3,
    		'GUEST_READY'=> 4,
    		'SWAP'=> 5,
    		'REGRET'=> 6,
    		'REGRET_ACK'=> 601,
    		'REGRET_NAK'=> 602,
				'GIVE_UP'=> 7,
				'GIVE_UP_ACK'=> 701,
				'DRAW'=> 8,
				'DRAW_ACK'=> 801,
				'DRAW_NAK'=> 802,
				);
		//global $USER_INFO;
		//echo 'user_info';
		//var_dump($USER_INFO);
	}
   
	function indexAction() 
	{ 
		echo $this->view->render('fivechess/index.html');//显示模版  
	}
	
	function roomAction()
	{
		global $USER_INFO;
//		echo 'user_info';
		if (!$USER_INFO)
		{
			$this->view->errMsg = '对不起，您还没有登陆';
			echo $this->view->render('auth/login.html');
			return false;
		}
		$username = $USER_INFO['username'];
//		var_dump($USER_INFO);
		$fivechessRoom = new FivechessRoom();
		$fivechessUser = new FivechessUser();
		$fivechess = new FiveChess();
		$authUser	 = new AuthUser();
//		$filter=new Zend_Filter_StripTags();
//		$room_id = $filter->filter($this->_request->getParam('room_id'));
		$fcUserInfo= $fivechessUser->GetUserRow($username);
		$room_id = $fcUserInfo->room_id;
		if (!$room_id)
		{
			echo '你不在任何房间中';
			return false;
		}
//		$gamingRowSet = $fivechess->GetRoomGaming($room_id);
	
		//get all the record
		//get the user infomation by this id
		$this->view->user = $USER_INFO;
//			$this->view->users = $user->getAllUser();
		//get the numbers of tables
//			$this->view->room_user = $fivechess->getRoom_join_User($your_id);
		$rooms = $fivechessRoom->find($room_id);
		$this->view->roomRow = $rooms[0];
//		var_dump($this->view->roomRow);
		$this->view->gamingRowSet = $fivechess->GetRoomGaming($room_id);
		$allUsers = Array();
		foreach ($this->view->gamingRowSet as $gaming)
		{
			if ($gaming->host_user)
			{
				$allUsers[$gaming->host_user] = 0;
			}
			if ($gaming->guest_user)
			{
				$allUsers[$gaming->guest_user] = 0;
			}
		}
		$username = $USER_INFO['username'];
		$fivechessRoom = new FivechessRoom();
		$fivechessUser = new FivechessUser();
		$fivechess = new FiveChess();
		$authUser	 = new AuthUser();
		$this->view->allUsers = $authUser->GetUsers($allUsers);
		$this->view->allUsers[''] = 0;
//		var_dump($this->view->gamingRowSet);
		$this->view->user_count = count($this->view->room_user);
		echo $this->view->render('fivechess/room.html');//显示模版  
		
	}
	
	function roomrefreshAction()
	{
		header('Content-Type: text/xml');
		header("Cache-Control: no-cache, must-revalidate");
		global $USER_INFO;
//		echo 'user_info';
		if (!$USER_INFO)
		{
			$this->view->errMsg = '对不起，您还没有登陆';
			echo $this->view->render('auth/login.html');
			return false;
		}
		$username = $USER_INFO['username'];
//		var_dump($USER_INFO);
		$fivechessRoom = new FivechessRoom();
		$fivechessUser = new FivechessUser();
		$fivechess = new FiveChess();
		$authUser	 = new AuthUser();
//		$filter=new Zend_Filter_StripTags();
//		$room_id = $filter->filter($this->_request->getParam('room_id'));
		$fcUserInfo= $fivechessUser->GetUserRow($username);
		$room_id = $fcUserInfo->room_id;
		if (!$room_id)
		{
			echo '你不在任何房间中';
			return false;
		}
//		$gamingRowSet = $fivechess->GetRoomGaming($room_id);
	
		//get all the record
		//get the user infomation by this id
		$this->view->user = $USER_INFO;
//			$this->view->users = $user->getAllUser();
		//get the numbers of tables
//			$this->view->room_user = $fivechess->getRoom_join_User($your_id);
		$rooms = $fivechessRoom->find($room_id);
//		var_dump($this->view->roomRow);
		$this->view->gamingRowSet = $fivechess->GetRoomGaming($room_id);
		$allUsers = Array();
		foreach ($this->view->gamingRowSet as $gaming)
		{
			if ($gaming->host_user)
			{
				$allUsers[$gaming->host_user] = 0;
			}
			if ($gaming->guest_user)
			{
				$allUsers[$gaming->guest_user] = 0;
			}
		}
		$username = $USER_INFO['username'];
		$fivechessRoom = new FivechessRoom();
		$fivechessUser = new FivechessUser();
		$fivechess = new FiveChess();
		$authUser	 = new AuthUser();
		$this->view->allUsers = $authUser->GetUsers($allUsers);
		$this->view->allUsers[''] = 0;
//		var_dump($this->view->gamingRowSet);
		$this->view->user_count = count($this->view->room_user);
		echo $this->view->render('fivechess/roomrefresh.html');
		return true;
	}
  
	function gameroomAction() 
	{ 
		global $USER_INFO;
		echo 'user_info';
		if (!$USER_INFO)
		{
			$this->view->errMsg = '对不起，您还没有登陆';
			echo $this->view->render('auth/login.html');
		}
		$username = $USER_INFO['username'];
		var_dump($USER_INFO);
		$fivechessRoom = new FivechessRoom();
		$fivechess = new FiveChess();
		$user	 = new AuthUser();
		$filter=new Zend_Filter_StripTags();
		$room_id = $filter->filter($this->_request->getParam('room_id'));
		$gamingRowSet = $fivechess->GetRoomGaming($room_id);
//		$your_id = $filter->filter(($this->_request->getParam('your_id')));
//		$your_id = $USER_INFO['id'];
		
		if($this->_request->isPost())	{//user login in and will find a table to sit down
			//get all the record
			//get the user infomation by this id
			$this->view->user = $USER_INFO;
//			$this->view->users = $user->getAllUser();
			//get the numbers of tables
//			$this->view->room_user = $fivechess->getRoom_join_User($your_id);
			$this->view->roomRow = $fivechessRoom->find($room_id);
			$this->view->gamingRowSet = $fivechess->GetRoomGaming($room_id);
			
			$this->view->user_count = count($this->view->room_user);
			echo $this->view->render('fivechess/gameroom.html');//显示模版  
		}
		else	{//ajax get url

			$method = $filter->filter(($this->_request->getParam('method')));
			$usertype = $filter->filter(($this->_request->getParam('usertype')));
			$table_id = $filter->filter(($this->_request->getParam('table')));;
			if($method == "set")	{
				$fivechess->setUser_ID_Zero('host',$your_id);
				$fivechess->setUser_ID_Zero('guest',$your_id);
				$data=array(
	    		$usertype.'_id'=>$your_id
					);
				$fivechess->updateChessBordByID($data,$table_id);
			}
			else if($method == "start")	{
				$status = 1;
				$data=array(
	    		'status'=>$status,
	    		'create_time'=>time(),
	    		'update_time'=>time()
					);
				$fivechess->updateChessBordByID($data,$id);
			}
			$gameroom = $fivechess->getGameRoom();
			$ret = "";
			foreach ($gameroom as $table)
			{
				
				$host_name = "";
				$host_face = 0;
				$guest_name = "";
				$guest_face = 0;
				//join all the infomation to a string.
				if($ret =="")
					$ret = $table['id']."|".$table['host_name']."|".$table['guest_name'];
				else
					$ret = $ret."!".$table['id']."|".$table['host_name']."|".$table['guest_name'];
			}
			echo $ret;
		}
	} 
	
	function chessboardAction()
	{
		global $USER_INFO;
			Zend_Loader::loadClass('Zend_Filter_StripTags');
			$filter=new Zend_Filter_StripTags();
			$id = 1;//$filter->filter(($this->_request->getParam('table')));
			$fivechess = new FiveChess();
			$boardinfo = $fivechess->getChessBordByID($id);
		if($this->_request->isPost())	{
			//fetch the data from the form
			//$id = 1;//$filter->filter(($this->_request->getParam('table')));
			$your_name = $filter->filter(($this->_request->getParam('your_name')));;
			//$your_id = $USER_INFO['id'];
			$host_user = $boardinfo['host_user'];//'hanframe';//$filter->filter(($this->_request->getPost('host_name')));
			$guest_user = $boardinfo['guest_user'];//'awang';//$filter->filter(($this->_request->getPost('guest_name')));
  		$next_user = $boardinfo['next_user'];//$filter->filter($this->_request->getPost('host_name'));
  		$prev_step = $boardinfo['prev_step'];
  		$status = $boardinfo['status']; //start game
			$step_no = $boardinfo['step_no'];  		
  		$chessboard = $boardinfo['chessboard'];
  		
  		$user = new AuthUser();
  		$host = $user->GetUserRow($host_user);
  		$guest = $user->GetUserRow($guest_user);
  		$fivechessuser = new FivechessUser();
  		$fivechessuser->AddUserInfo($host['id'],$host_user);
  		$fivechessuser->AddUserInfo($guest['id'],$guest_user);
  		
			$count = $fivechess->countByID($id);
			$data=array(
  			'id'=>$id,
				'host_user'=>$host_user,
				'guest_user'=>$guest_user,
    		'next_user'=>$next_user,
    		'step_no'=>$step_no,
    		'prev_step'=>$prev_step,
				'status'=>$status,
				'chessboard'=>$chessboard,
				'update_time'=>time()
				);
			$this->view->fivechess = $data;
			unset($data);
			//get the hostname and guestname
			$user = new AuthUser();
			
			$this->view->user_name = $your_name;
			$this->view->next_user = $next_user;
			//get curr chess infomation
			echo $this->view->render('fivechess/chessboard.html');//show the fivechess bord 
		}
		else	{   
			$ret =  "NotUpdate";	//return value;
			//$user = new AuthUser();
			$id = $filter->filter(($this->_request->getParam('table')));
			$user = $filter->filter(($this->_request->getParam('user'))); // the username 
			//user has do a chess,record the seat for prev_step
			$seat = $filter->filter(($this->_request->getParam('seat')));
			$method = $filter->filter(($this->_request->getParam('method')));
			switch($method)	{
				//if ajax request for get the webpage
				case "init":
					$ret = "Init|".$boardinfo['status'];
				break;
				case "get":
					//return from curr status
					switch($boardinfo['status'])	{
						case $this->CHESS_STATUS['GAME_OVER']:
							$ret = "GameOver|";
						break;
						case $this->CHESS_STATUS['GAME_PLAYING']:
							if($boardinfo['next_user'] == $user && $boardinfo['prev_step'] != $seat && $boardinfo['prev_step'] != 0) 
								$ret = "Updated|".$boardinfo['step_no']."|".$boardinfo['prev_step'];
						break;
						case $this->CHESS_STATUS['HOST_READY']:
						break;
						case $this->CHESS_STATUS['GUEST_READY']:
						break;
						case $this->CHESS_STATUS['SWAP']:
						break;
						case $this->CHESS_STATUS['REGRET']:
							$ret = "REGRET";
						break;
						case $this->CHESS_STATUS['GIVE_UP']:
							if($boardinfo['next_user'] != $user)
								$ret = "Give_Up|";
						break;
						case $this->CHESS_STATUS['DRAW']:
								$ret = "DRAW";
						break;
					}
					/*
				//status == 0 stand for gameover ,else if has update ,will return the update data to user
					if($boardinfo['status'] == 0)
					else if($boardinfo['next_user'] == $user && $boardinfo['prev_step'] != $seat && $boardinfo['prev_step'] != 0) 
						$ret = "Updated|".$boardinfo['prev_step'];
					*/
				break;
				//when user decide a seat and choose a chess,will update the database
				case "set":
					if($boardinfo['status'] == 1)	{//status == 1 stand for game playing now
						$data['next_user'] = ($user == $boardinfo['host_user']) ? $boardinfo['guest_user'] : $boardinfo['host_user'];
						$data['chessboard'] = $fivechess->setChessboardVal($boardinfo['chessboard'], $seat, $boardinfo['step_no']);
						$data['step_no'] = $boardinfo['step_no'] + 1;
						$data['prev_step'] = $seat;
					}
				break;
				//when a user has win this game,handle the scores and express
				case "win":
					if($boardinfo['status'] == 1)	{//status == 1 stand for game playing now
						$data['next_user'] = ($user == $boardinfo['host_user']) ? $boardinfo['guest_user'] : $boardinfo['host_user'];
						$data['chessboard'] = $fivechess->setChessboardVal($boardinfo['chessboard'], $seat, $boardinfo['step_no']);
						$data['step_no'] = $boardinfo['step_no'] + 1;
						$data['prev_step'] = $seat;
					}
					else if($boardinfo['status'] == $this->CHESS_STATUS['GIVE_UP'])
						$data['status'] = $this->CHESS_STATUS['GIVE_UP_ACK'];
					else
						$ret = "UpdateOK|".$method;
					//add the user's scores and express
					$fivechessuser = new FivechessUser();
					$fivechessuser->AddWin($user);
				break;
				/*
				 *when a user has losed in this game,handle the scores and express 
				 *and clear all the user's data
				*/
				case "lose":
					//clear all the data
					$data['next_user'] = "";
					$data['step_no'] = 0;
					$data['prev_step'] = 0;
					$data['status'] = 0;
					$data['chessboard'] = "";
					//reduce the user's scores and express
					$fivechessuser = new FivechessUser();
					$fivechessuser->AddFail($user);
				break;
				//menu function for start game
				case "start":
					if($boardinfo['status'] == 1)	{	
						/* user want to start game,when status change to 1,tell user can start game now
						*/
						$ret = "GameGo|".$boardinfo['host_user']."|".$boardinfo['guest_user']."|";
					}
					else if(($boardinfo['status'] == 3 && $user ==  $boardinfo['guest_user']) || ($boardinfo['status'] == 4 && $user ==  $boardinfo['host_user']))	{
						//has the other user ready to game,so start the game, and notice the other user.
						$data['host_user'] = $boardinfo['guest_user'];
						$data['guest_user'] = $boardinfo['host_user'];
						$data['next_user'] = $data['host_user'];
						$data['step_no'] = 1;
						$data['prev_step'] = 0;
						$data['status'] = 1;
					}
					else	{// only a user ready to start game, record this request in database.
						$status = ($user == $boardinfo['host_user']) ? 3 : 4 ;
						if($boardinfo['status'] != $status)	{
							$data['status'] = $status;
							$fivechess->updateChessBordByID($data,$id);
							$ret = "UpdateOK|start|";
						}
					}
				break;
				case "give_up":
					if($boardinfo['status'] == 1)	{	
						$data['status'] = $this->CHESS_STATUS['GIVE_UP'];
					}
					else if($boardinfo['status'] == $this->CHESS_STATUS['GIVE_UP_ACK'])	{
						//if($boardinfo['next_user'] == $user)
							$ret = "GIVE_UP_ACK|";
					}
				break;
				//handle all the user's draw request
				case "draw"://user apply for draw this chess
					if($boardinfo['status'] == 1)	{	
						$data['status'] = $this->CHESS_STATUS['DRAW'];
					}
					else if($boardinfo['status'] == $this->CHESS_STATUS['DRAW_ACK'])	{
						$ret = "DRAW_ACK";
					}
					else if($boardinfo['status'] == $this->CHESS_STATUS['DRAW_NAK'])	{
						$ret = "DRAW_NAK";
					}
				break;
				case "draw_ack": // user agree draw this chess
					$data['status'] = $this->CHESS_STATUS['DRAW_ACK'];
				break;
				case "draw_nak": // user don't agree draw this chess
					$data['status'] = $this->CHESS_STATUS['DRAW_NAK'];
				break;
				case "draw_ok":
					//clear all the data
					$data['next_user'] = "";
					$data['step_no'] = 0;
					$data['prev_step'] = 0;
					$data['status'] = 0;
					$data['chessboard'] = "";
					$fivechessuser = new FivechessUser();
					$fivechessuser->AddDraw($boardinfo['host_user']);
					$fivechessuser->AddDraw($boardinfo['guest_user']);
				break;
				case "draw_deny":
					$data['status'] = $this->CHESS_STATUS['GAME_PLAYING'];
				break;
				//handle all the user's regret request
				case "regret"://user apply for regret this chess
					if($boardinfo['status'] == 1)	{	
						$data['status'] = $this->CHESS_STATUS['REGRET'];
					}
					else if($boardinfo['status'] == $this->CHESS_STATUS['REGRET_ACK'])	{
						$ret = "REGRET_ACK";
					}
					else if($boardinfo['status'] == $this->CHESS_STATUS['REGRET_NAK'])	{
						$ret = "REGRET_NAK";
					}
				break;
				case "regret_ack": // user agree draw this chess
					$data['status'] = $this->CHESS_STATUS['REGRET_ACK'];
				break;
				case "regret_nak": // user don't agree draw this chess
					$data['status'] = $this->CHESS_STATUS['REGRET_NAK'];
				break;
				case "regret_ok":
					//clear all the data
					$data['step_no'] = $boardinfo['step_no'] - 2;
					$tmparray = explode("|",$boardinfo['chessboard']);//split("|", $boardinfo['chessboard']);
					$data['prev_step'] = $tmparray[sizeof($tmparray) - 1] ;
					$data['status'] = $this->CHESS_STATUS['GAME_PLAYING'];
					$data['chessboard'] = $fivechess->regretChessboard($boardinfo['chessboard']);
				break;
				case "regret_deny":
					$data['status'] = $this->CHESS_STATUS['GAME_PLAYING'];
				break;
			}
			
			if(isset($data))	{//if has any update data, will update the database
				$fivechess->updateChessBordByID($data,$id);
				if( $data['status'] == 0)
					$ret = "GameOver|";
				else
					$ret = "UpdateOK|".$method;
				unset($data);
			}
			echo $ret;
			/*
			if($method == "get")	{
				if($boardinfo['status'] == 0)
					$ret = "GameOver|";
				else if($boardinfo['next_user'] == $user && $boardinfo['prev_step'] != $seat && $boardinfo['prev_step'] != 0) 
					$ret = "Updated|".$boardinfo['prev_step'];
			}
			else	if($method == "set" || $method == "win" || $method == "lose" || $method == "start"){
				$next_user = ($user == $boardinfo['host_user']) ? $boardinfo['guest_user'] : $boardinfo['host_user'];
				//set chessboard infomation
				$step_no = $boardinfo['step_no'];
				$chessboard = $fivechess->setChessboardVal($boardinfo['chessboard'], $seat, $step_no);
				if($boardinfo['status'] == 1)
					$step_no++;
				if($method == "win")	{
					$fivechessuser = new FivechessUser();
					$fivechessuser->AddWin($user);
				}
				else if($method == "lose")	{
					$fivechessuser = new FivechessUser();
					$fivechessuser->AddFail($user);
					$next_user = "";
					$step_no = 0;
					$seat = 0;//prev_step
					//$status = 2;
					$data['status'] = 2;
					$chessboard = "";
				}
				else if($method == "start")	{
					if($boardinfo['status'] == 1)	{
						echo "GameGo|".$boardinfo['host_user']."|".$boardinfo['guest_user']."|";
						return ;
					}
					else if(($boardinfo['status'] == 3 && $user ==  $boardinfo['guest_user']) || ($boardinfo['status'] == 4 && $user ==  $boardinfo['host_user']))	{
						$data['host_user'] = $boardinfo['guest_user'];
						$data['guest_user'] = $boardinfo['host_user'];
						$next_user = $data['host_user'];
						$step_no = 1;
						$seat = 0;
						//$status = 1;
						$data['status'] = 1;
					}
					else 	{
						$status = ($user == $boardinfo['host_user']) ? 3 : 4 ;
						if($boardinfo['status'] != $status)	{
							$data['status'] = $status;
							$fivechess->updateChessBordByID($data,$id);
							echo "UpdateOK|start|";
						}
						return ;
					}
				}
				else
					$status = $boardinfo['status'];
					
				$data['next_user'] = $next_user;
				$data['step_no'] = $step_no;
				$data['prev_step'] = $seat;
				//$data['status'] = $status;
				$data['chessboard'] = $chessboard;
				
				$fivechess->updateChessBordByID($data,$id);
				if($boardinfo['status'] == 2 || $data['status'] == 2)
					$ret = "GameOver|";
				else if($boardinfo['status'] == 1)
					$ret = "UpdateOK|".$method;
				unset($data);
			}
			echo $ret; 
			*/
		}
	}
}
	
	
	